<?php

namespace plugin\muadmin\app\common\core;

use plugin\muadmin\app\common\model\Admin;
use plugin\muadmin\app\common\model\AuthGroup;
use plugin\muadmin\app\common\model\AuthGroupAccess;
use plugin\muadmin\app\common\model\AuthRule;

class AdminAuth
{
    protected static $instance;//单例模式
    protected $error = '';//错误信息
    public $id;
    public $userName;
    protected $_user;
    protected $session_key = 'admin_id';

    public function getError()
    {
        return  $this->error;
    }
    public static function getInstance()
    {
        if(!self::$instance){
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 检测是否登录
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function isLogin()
    {
        $admin_id = session($this->session_key);
//        print_r('admin_id'.$admin_id);
        if(empty($admin_id)){
            $this->error = '未登录';
            return false;
        }
        $admin = Admin::where('id',$admin_id)->find();
        if(empty($admin)){
            $this->error = '用户不存在';
            return false;
        }
        if($admin->status != 1){
            $this->error = '用户被禁用';
            return false;
        }
        $this->id = $admin_id;
        $this->userName = $admin->username;
        $this->_user = $admin;
        return true;
    }

    /**
     * 获取用户信息
     * @return null
     */
    public function getUserInfo()
    {
        $res =  $this->_user?->toArray();
        if(isset($res['password'])){
            unset($res['password']);
        }
        return $res;
    }

    /**
     * 登录
     * @param string $username
     * @param string $password
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function login(string $username,string $password)
    {
        $admin = Admin::where('username',$username)->find();
        if(empty($admin)){
            $this->error = '用户不存在';
            return false;
        }
        if(verify_password($password,$admin->password,$admin->salt)){
            $session = request()->session();
            $session->set($this->session_key,$admin->id);
            $admin->logintime = time();
            $admin->loginip = request()->getRealIp(true);
            $admin->save();
            return true;
        }else{
            $this->error = '密码错误';
            return false;
        }
    }
    public function logout()
    {
        $session = request()->session();
        $session->forget($this->session_key);
        return true;
    }
    public function getAdminMenu($isMenu = true)
    {
        $groups = AuthGroupAccess::where('uid',$this->_user->id)
            ->column('group_id');
        $rulesIds = AuthGroup::where('id','in',$groups)
            ->column('rules');
        $rulesIds = array_unique(array_filter(explode(',',implode(',',$rulesIds))));
        if(in_array('*',$rulesIds)){
            $where = [
                ['status','=',1]
            ];
        }else{
            $where = [
                ['status','=',1],
                ['id','in',$rulesIds]
            ];
        }
        if($isMenu){
            $where[] = ['ismenu','=',1];
        }
        $rules = AuthRule::where($where)
            ->order('id asc,weigh desc')
            ->select()
            ->toArray();

        return $rules;
    }

    /**
     * 获取用户组权限
     * @param $groupId
     * @param $getPid
     * @param $isMenu
     * @return array
     */
    public function getGroups($groupId = 1,$getPid=false,$isMenu = true)
    {
        if($getPid){
            $groupId = AuthGroup::where('id',$groupId)
                ->value('pid');
        }
        $rulesIds = AuthGroup::where('id','in',$groupId)
            ->column('rules');
        $rulesIds = array_unique(array_filter(explode(',',implode(',',$rulesIds))));
        if(in_array('*',$rulesIds)){
            $where = [
                ['status','=',1]
            ];
        }else{
            $where = [
                ['status','=',1],
                ['id','in',$rulesIds]
            ];
        }
        if($isMenu){
            $where[] = ['ismenu','=',1];
        }
        $rules = AuthRule::where($where)
            ->order('id asc,weigh desc')
            ->select()
            ->toArray();

        return $rules;
    }
}